#include "visitingnodewidget.h"

VisitingNodeWidget::VisitingNodeWidget(QWidget *parent)
    : QWidget{parent}
{
    setFixedHeight(600);
    m_layout = new QVBoxLayout;
    setLayout(m_layout);
    m_emptyLabel = new QLabel("空空如也~");
    m_layout->addWidget(m_emptyLabel);
    m_layout->addStretch();
}

void VisitingNodeWidget::addNodeUnit(myNode *node) {
    if (m_nodeNum == 0) {
        m_layout->removeWidget(m_emptyLabel);
        m_emptyLabel->close();
    }
    ++m_nodeNum;
    nodeUnit *unit = new nodeUnit(node);
    connect(unit, &nodeUnit::nodeUnitRemoved, this, &VisitingNodeWidget::removeNodeUnit);
    m_layout->insertWidget(m_nodeNum - 1, unit);
}

void VisitingNodeWidget::removeNodeUnit(int ID) {
    --m_nodeNum;
    if (m_nodeNum == 0) {
        m_emptyLabel->show();
        m_layout->insertWidget(0, m_emptyLabel);
    }
    emit nodeUnitRemoved(ID);
}

nodeUnit::nodeUnit(myNode *node, QWidget *parent)
    : QWidget(parent) {
    m_ID = node->getID();
    setFixedHeight(75);
    QHBoxLayout *mainLayout = new QHBoxLayout;
    setLayout(mainLayout);
    QLabel *nameLabel = new QLabel(QString::fromUtf8(node->getName()));
    mainLayout->addWidget(nameLabel);
    QPushButton *removeButton = new QPushButton("移除");
    removeButton->setFixedSize(100,50);
    connect(removeButton, &QPushButton::clicked, this, [this]() {
        emit nodeUnitRemoved(m_ID);
        delete this;
    });
    mainLayout->addWidget(removeButton);
}
